/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, remove the copyright
 * infomation is regarded invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.action;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.hibernate.Transaction;

import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.bo.MrIaskCategoryStatistics;
import com.mr.qa.bo.Question;
import com.mr.qa.bo.QuestionCategory;
import com.mr.qa.dao.impl.QuestionCategoryDAO;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.BaseForm;
import com.mr.qa.form.QuestionCategoryForm;
import com.mr.qa.util.HibernateSessionFactory;

public class AdminAction extends BaseAction
{
    private static final Log log = LogFactory.getLog(AdminAction.class);
    public AdminAction() {
    }
    public ActionForward doAction(ActionMapping mapping, ActionForm form,
                        HttpServletRequest request, HttpServletResponse response) throws QaException
    {
        ActionForward af = null;
        UserSession us = UserSessionUtil.getUserSession(request);
        ActionMessages errors = new ActionMessages();
        ActionMessages messages = new ActionMessages();
        String action = this.getAction(request);
        QuestionCategoryForm categoryForm = (QuestionCategoryForm)form;
        if(us == null || !"1".equals(us.getType())) {
            af = mapping.findForward("relogin");
            errors.add("noright", new ActionMessage("user.noright"));
            saveErrorsAndMessages(af,errors,messages,request);
            return af;
        }
        if("premigr".equals(action)) {
            af = preMigration(mapping,categoryForm,errors,messages,request);
        }
        else if("confirmmigr".equals(action)) {
            String from = request.getParameter("from");
            String to = request.getParameter("to");
            af = migration(from,to,mapping,form,errors,messages,request);
            String path = af.getPath();
            path = path.replace("!?",""+categoryForm.getType());
            af = new ActionForward(path);
            af.setRedirect(true);
        }
        else {
            af = mapping.findForward("index");
        }
        saveErrorsAndMessages(af,errors,messages,request);
        request.setAttribute("type", categoryForm.getType());
        return af;
    }
    
    private ActionForward preMigration(ActionMapping mapping, QuestionCategoryForm form,
                        ActionMessages errors,ActionMessages messages,HttpServletRequest request) 
    {
        ActionForward af = null;
        try 
        {
            Transaction tx = null;
            BaseForm baseForm = (BaseForm)form;
            List list = null;
            QuestionCategoryDAO categoryDAO = new QuestionCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            list = categoryDAO.findAll("order by type");//level 1
            tx.commit();
            request.setAttribute("rootQuestionCategories",list);
            af = mapping.findForward(baseForm.getAction());
        }
        catch(Exception e) 
        {
            log.error(e);            
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return af;
    }
    private ActionForward migration(String fromQuestionCategoryId,
    String toQuestionCategoryId,
    ActionMapping mapping, ActionForm form,ActionMessages errors,
    ActionMessages messages,HttpServletRequest request) 
    {
        ActionForward af = null;
        Transaction tx = null;
        String toQuestionCategoryName = null;
        String fromQuestionCategoryName = null;
        try 
        {
            BaseForm baseForm = (BaseForm)form;
            Set<Question> list = null;
            QuestionCategory from = null;
            QuestionCategory to = null;
            QuestionCategoryDAO categoryDAO = new QuestionCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            
            from = categoryDAO.findById(new Integer(fromQuestionCategoryId));
            fromQuestionCategoryName = from.getName();
            MrIaskCategoryStatistics froms = from.getMrIaskCategoryStatistics();
            
            to = categoryDAO.findById(new Integer(toQuestionCategoryId));
            toQuestionCategoryName = to.getName();
            MrIaskCategoryStatistics tos = to.getMrIaskCategoryStatistics();
            
            list = from.getMrIaskQuestions();
            for(Question q:list) 
            {
                q.setMrIaskCategory(to);
                //1 persist
                HibernateSessionFactory.getSession().update(q);
            }
            //
            froms.setTotal(froms.getTotal()-list.size());
            //
            tos.setTotal(tos.getTotal()+list.size());
            //2 persist
            HibernateSessionFactory.getSession().update(from);
            //3 persist
            HibernateSessionFactory.getSession().update(to);
            tx.commit();

            af = mapping.findForward(baseForm.getAction());
            messages.add("migration.success",new ActionMessage(
            "questions.migration.success",list.size(),
            from.getId()+":"+from.getName(),to.getId()+":"+to.getName()));
        }
        catch(Exception e) 
        {
            if(tx !=null)tx.rollback();
            log.error(e);
            messages.add("migration.failure",new ActionMessage(
            "questions.migration.failure",fromQuestionCategoryId+":"+fromQuestionCategoryName
            ,toQuestionCategoryId+":"+fromQuestionCategoryName));
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return af;
    }
}
